package com.jwell.bigdata.presenter

import com.jwell.bigdata.base.BasePresenter
import com.jwell.bigdata.comment.BigDataApp
import com.jwell.bigdata.comment.ConstValue
import com.jwell.bigdata.contract.LoginContract
import com.jwell.bigdata.model.LoginModel
import com.jwell.bigdata.utils.BaseSubscriber
import com.jwell.bigdata.utils.MD5
import com.jwell.bigdata.utils.SPUtils
import com.jwell.bigdata.utils.ToastUtils
import org.json.JSONObject
import org.reactivestreams.Subscription

/**
 * Created by 76577 on 2018/4/8.
 * 电子磅单列表查询
 */
class LoginPresenter : LoginContract.Presenter, BasePresenter<LoginContract.View>() {

    override fun checkLogin() {
        var cookieString=SPUtils.getString(BigDataApp.instance,ConstValue.TOKEN_URL,"")
        mLoginModel.checkLogin(cookieString,object :BaseSubscriber(){
            override fun setSubscription(s: Subscription) {
                mSubscription = s
            }

            override fun succeed(data: JSONObject) {
              System.out.println(data.toString())
                getView()?.hideProgress()
                getView()?.checkLogin(true,cookieString)

            }

            override fun onFailed(msg: String) {
                getView()?.hideProgress()
                getView()?.checkLogin(false,"")
            }
        })
    }

    override fun login(account: String, pass: String) {

        mLoginModel.login(account,MD5(pass).md5_32,object :BaseSubscriber(){
            override fun succeed(data: JSONObject) {
                System.out.println(data.toString())
                getView()?.hideProgress()

                SPUtils.putString(BigDataApp.instance,ConstValue.ACCOUNT,account)
                var ticket=JSONObject(data.get("data").toString()).getString("cookie")
                var cookieString=ticket.split("=")[1];
                SPUtils.putString(BigDataApp.instance,ConstValue.TOKEN_URL,cookieString)
                getView()?.loginSuccess(cookieString)
            }

            override fun onFailed(msg: String) {
                getView()?.hideProgress()
                ToastUtils.showCenterToast(BigDataApp.instance,msg)
            }

            override fun setSubscription(s: Subscription) {
                mSubscription = s
            }
        })
    }

    private val mLoginModel: LoginModel by lazy {
        LoginModel()
    }
}